local onmax = function(self, max)
    self.inst.replica.stamina:SetMax(max)
end
local oncurrent = function(self, current)
    self.inst.replica.stamina:SetCurrent(current)
end

local Stamina = Class(function(self, inst)
        self.inst = inst
        -- 初始上限 = 80 + 等级
        self.max = 80
        -- 当前体力初始化为上限
        self.current = 80
    end,
    nil,
    {
        max = onmax,
        current = oncurrent,
    })

-- 限制数值范围
local function clamp(x, minv, maxv)
    return x < minv and minv or (x > maxv and maxv or x)
end

-- 设置新的上限
function Stamina:SetMax(val)
    self.max = val
    -- 如果当前值超过新上限，截断
    if self.current > self.max then
        self.current = self.max
    end
end

-- 设置当前体力
function Stamina:SetCurrent(val)
    self.current = clamp(val, 0, self.max)
end

-- 扣体力（例如被攻击时调用）
function Stamina:DoDelta(delta)
    self:SetCurrent(self.current + delta)
end

function Stamina:OnSave()
    return {
        max = self.max,
        current = self.current,
    }
end

function Stamina:OnLoad(data)
    if data then
        self.max = data.max or 80
        self.current = data.current or 80
        -- 设置新的上限
        self:SetMax(self.max)
        -- 设置当前体力
        self:SetCurrent(self.current)
    end
end

return Stamina
